package com.cavy.platform.server.controller;

import com.cavy.platform.server.ResultInfo;
import com.cavy.platform.server.domain.AbstractConfigMap;
import com.cavy.platform.server.dto.FileConfigMapCreateDto;
import com.cavy.platform.server.dto.StringConfigMapCreateDto;
import com.cavy.platform.server.service.ConfigMapService;
import com.cavy.platform.server.validator.WorkspaceExist;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@RequestMapping("/{workspace}/configMap")
public class ConfigMapController {
    @Autowired
    private ConfigMapService service;

    //创建
    @PostMapping(params = {"type=STRING"})
    public ResultInfo createString(@RequestBody @Valid StringConfigMapCreateDto dto) {
        service.create(dto);
        return ResultInfo.newSuccess();
    }

    //创建
    @PostMapping(params = {"type=FILE"})
    public ResultInfo createFile(@RequestBody @Valid FileConfigMapCreateDto dto) {
        service.create(dto);
        return ResultInfo.newSuccess();
    }

    //上传文件
    @PostMapping("{name}/upload")
    public ResultInfo uploadFile(@PathVariable(name = "workspace") @Valid @WorkspaceExist @NotBlank String workspace,
                                 @PathVariable @Valid @NotBlank String name,
                                 @Valid @NotNull MultipartFile file) {
        service.upload(file, workspace, name);
        return ResultInfo.newSuccess();
    }

    //详情
    @GetMapping("{name}/info")
    public AbstractConfigMap info(@PathVariable(name = "workspace") @Valid @WorkspaceExist @NotBlank String workspace,
                                  @PathVariable String name) {
        return service.info(workspace, name);
    }

    //列表
    @GetMapping("list")
    public List<AbstractConfigMap> list(@PathVariable(name = "workspace") @Valid @WorkspaceExist @NotBlank String workspace, String key) {
        return service.list(workspace, key);
    }

    //获取值
    @GetMapping("{name}/value")
    public void getValue(@PathVariable(name = "workspace") @Valid @WorkspaceExist @NotBlank String workspace,
                         @PathVariable(name = "name") @Valid @NotBlank String name, HttpServletResponse response) {
        service.getValue(workspace, name, response);
    }

    //删除
    @PostMapping("{name}/delete")
    public ResultInfo delete(@PathVariable(name = "workspace") @Valid @WorkspaceExist @NotBlank String workspace,
                             @PathVariable @Valid @NotBlank String name) {
        service.delete(workspace, name);
        return ResultInfo.newSuccess();
    }
}
